package manager

import (
	"fmt"
	"net"

	"github.com/clebeg/gochat/protocol"
)

type UserInfo struct {
	Conn net.Conn
	protocol.UserProfile
	RemoteAddr string
}

// 用户管理者
type UserManager struct {
	OnlineUsers     map[int]*UserInfo
	OnlineUserAddrs map[string]int
}

var UserMgr = &UserManager{
	OnlineUsers:     make(map[int]*UserInfo, 128),
	OnlineUserAddrs: make(map[string]int, 128),
}

// 添加在线用户
func (u *UserManager) AddOnlineUser(userProfile protocol.UserProfile,
	conn net.Conn) {
	userInfo := &UserInfo{
		Conn:        conn,
		UserProfile: userProfile,
		RemoteAddr:  conn.RemoteAddr().String(),
	}
	u.OnlineUsers[userProfile.Username] = userInfo

	u.OnlineUserAddrs[conn.RemoteAddr().String()] = userInfo.Username
}

// 删除在线用户
func (u *UserManager) RemoveOnlineUser(userProfile protocol.UserProfile) {
	up, ok := u.OnlineUsers[userProfile.Username]

	if ok {
		delete(u.OnlineUsers, userProfile.Username)
		delete(u.OnlineUserAddrs, up.RemoteAddr)
	}
}

// 获取某一个在线用户的处理器
func (u *UserManager) GetOneOnlineUser(userProfile protocol.UserProfile) (up *UserInfo,
	err error) {
	up, ok := u.OnlineUsers[userProfile.Username]

	if !ok {
		err = fmt.Errorf("此用户不在线，用户名=%d", userProfile.Username)
		return
	}
	return
}
